package com.qiyun.dinghuohui.utils;

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRoute;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class HttpDataFetcher {
	private static HttpDataFetcher mFetcher = new HttpDataFetcher();
	private static final String TAG = "Http Data Fetcher";
	private static final String JSON_DATA = "jsonData";

	private static final int mTimeoutConnection = 30 * 1000;
	private static final int mTimeoutSocket = 30 * 1000;

	public static final String STATUS_KEY = "RESULT_STATUS";
	private static final Integer SUCCESS = Integer.valueOf(0);
	private static final Integer FAIL = Integer.valueOf(1);

	private static JSONObject FAIL_JSON = new JSONObject();

	private HttpDataFetcher() {

	}

	public static HttpDataFetcher getInstance() {
		// if (mFetcher==null){
		mFetcher = new HttpDataFetcher();
		// }
		return mFetcher;
	}

	public final JSONObject postData(String mainUrl, String subUrl, Object parameters) {
		DefaultHttpClient mHttpClient = null;
		try {
			// 创建 HttpParams 以用来设置HTTP 参数
			HttpParams params = new BasicHttpParams();
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, "UTF-8");
			HttpProtocolParams.setUseExpectContinue(params, true);
			HttpProtocolParams.setUserAgent(params, "BiBeiForAndroid/1.0.0.0");
			// Make pool
			ConnPerRoute connPerRoute = new ConnPerRouteBean(12);
			ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);
			ConnManagerParams.setMaxTotalConnections(params, 20);
			// 设置连接超时和 Socket 超时，以及 Socket 缓存大小
			HttpConnectionParams.setStaleCheckingEnabled(params, false);
			HttpConnectionParams.setConnectionTimeout(params, mTimeoutConnection);
			HttpConnectionParams.setSoTimeout(params, mTimeoutSocket);
			HttpConnectionParams.setSocketBufferSize(params, 10 * 1024);
			// Some client params
			HttpClientParams.setRedirecting(params, false);
			// Register http/s shemas!
			SchemeRegistry schReg = new SchemeRegistry();
			schReg.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			schReg.register(new Scheme("https", SSLSocketFactory
					.getSocketFactory(), 443));
			ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
					params, schReg);
			mHttpClient = new DefaultHttpClient(conMgr, params);

			List<NameValuePair> formParams = new ArrayList<NameValuePair>();
			formParams.add(new BasicNameValuePair(JSON_DATA, parameters
					.toString()));

			HttpEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");
			Log.i(TAG, mainUrl + subUrl);
			HttpResponse httpResponse = null;
			HttpPost request = new HttpPost(mainUrl + subUrl);
			request.setEntity(entity);

			HttpParams httpParameters = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParameters,
					mTimeoutConnection);
			HttpConnectionParams.setSoTimeout(httpParameters, mTimeoutSocket);

			mHttpClient = new DefaultHttpClient(httpParameters);
			request.addHeader("accept-encoding", "gzip,deflate");
			request.addHeader("Connection", "close");
			httpResponse = mHttpClient.execute(request);

			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String retSrc = EntityUtils.toString(httpResponse.getEntity());
				mHttpClient.getConnectionManager().shutdown();
				return genSuccessResult(new JSONObject(retSrc));
			} else {
				Log.e("", "********< error >********: server return code:"
						+ httpResponse.getStatusLine().getStatusCode());
				mHttpClient.getConnectionManager().shutdown();
				return genFailResult(); // modify by ccc at 2011-12-08
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (mHttpClient != null) {
				mHttpClient.getConnectionManager().shutdown();
			}
		}
		return genFailResult();// modify by ccc at 2011-12-22
	}

	private static JSONObject genSuccessResult(JSONObject result) {
		try {
			return result.put(STATUS_KEY, SUCCESS);
		} catch (JSONException e) {
			throw new RuntimeException(e);
		}
	}

	private static JSONObject genFailResult() {
		return FAIL_JSON;
	}
}
